import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    path: '/playground',
    component: () => import('@/views/playground')
  },
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard', // /dashboard
        component: () => import('@/views/dashboard')
      },
      {
        path: 'article', // /article
        component: () => import('@/views/article')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 前置守卫：任何路由进入前都需要经过它，它允许 才可进入
const whitePage = ['/login']
router.beforeEach((to, from, next) => {
  // 进入除登陆以外所有页面都要有token才可进入
  if (store.state.token) {
    next()
  } else {
    if (whitePage.includes(to.path.toLowerCase())) {
      next()
    } else {
      next('/login')
    }
  }
})
// 后置守卫：已进入到想去的路由了
router.afterEach((to, from) => {})
// 获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
// 修改原型对象中的push方法
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
export default router
